package com.edu.hre.db.sql.recruit;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.db.pojo.HreCandidateSkill;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.recruit.CanSkillForm;
import com.edu.hre.struts.form.recruit.CanSkillListForm;

public class CanSkillDAOService implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3394301416150421253L;
	public static final String BEAN_NAME = "canSkillDAOService";
	private BaseService baseService  = null;

	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}

	public ArrayList<CanSkillForm> getCanSkillList(int limit, int offset, int canId){

		ArrayList<CanSkillForm> listResult = new ArrayList<CanSkillForm>();

		String sql = "SELECT eski.id AS col1," +
					" ski.name AS col2," +
					" eski.years_of_exp AS col3," +
					" eski.comments AS col4" +

					" FROM hre_candidate_skill AS eski" +
					" LEFT OUTER JOIN hre_skill AS ski ON eski.skill_id = ski.id" +
					" LEFT OUTER JOIN hre_job_candidate AS can ON eski.candidate_id = can.id " +

					" WHERE can.is_deleted = 0 " +
					" AND can.id = ? " +
					" ORDER BY eski.date_created DESC";
		
		List <Object[]> listObject = baseService.listArrayObject(sql, limit, offset, canId);
		for(int i = 0; listObject != null && i < listObject.size(); i++){

			try {

				Object[] objs = listObject.get(i);
				CanSkillForm skill = new CanSkillForm();
	
				skill.setId(Integer.parseInt(CommonUtils.normalizeObjectToString(objs[1], "0")));
				skill.setCanId(canId);
				skill.setSkill(CommonUtils.normalizeObjectToString(objs[2], ""));
				skill.setYear(String.format("%5.1f", Double.parseDouble(CommonUtils.normalizeObjectToString(objs[3], "0"))));
				skill.setComment(CommonUtils.normalizeObjectToString(objs[4], ""));

				listResult.add(skill);
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
		
		return listResult;
	}

	public int countCanSkills(int canId){

		int count = baseService.countByColumns(new String[]{"candidateId"}, new int[]{Compare.EQUAL}, new Integer[]{canId}, "id", HreCandidateSkill.class);
		return count < 0 ? 0 : count;
	}

	public void deleteSkills(CanSkillListForm form){

		ArrayList<CanSkillForm> info = (ArrayList<CanSkillForm>) form.getAllSkills();

		for (int i = 0; i < info.size(); i++) {
			
			try {

				CanSkillForm work = info.get(i);
				if (work.isSelected()) {
					baseService.deleteFirstPojo("id", Compare.EQUAL, (long) work.getId(), null, null, 0, HreCandidateSkill.class);
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
	}
}
